<!--
 * @Description: 菌群检测
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-04-10
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-05-20
-->
<script lang="ts" setup>
  import { onShareAppMessage, onShow } from '@dcloudio/uni-app'
  import { computed, ref, watch } from 'vue'

  import { requestGetUserDetectionInfoList, requestProductScan, requestScan } from '@/api/business/tracecode/detectionInfo'
  import { HttpCodeEnum } from '@/enum/httpEnum'
  import { indexSortPng, microbiotaPng } from '@/enum/imageEnum'
  import { HOME_PAGE } from '@/enum/pageEnum'
  import { SHARE_HOME_IMAGE, SHARE_HOME_TITLE } from '@/enum/shareEnum'
  import { SCAN_TYPE, scanResultLink, scanTypeDesc, scanTypeResult, STATUS_DETECTION_ENUM } from '@/enum/statusResultsEnum'
  import env from '@/env/index'
  import { useUserInfoStore } from '@/stores/userInfo'
  import { checkLogin } from '@/utils/auth'
  import { isImage, openDocument } from '@/utils/util'

  const userInfoStore = useUserInfoStore()
  const data: any = ref([])
  const isLogin = computed(() => {
    return checkLogin()
  })
  watch(
    () => isLogin.value,
    (newVal) => {
      if (newVal) getUserDetectionInfoList()
    },
  )
  onShow(() => {
    if (isLogin.value) {
      getUserDetectionInfoList()
    }
  })
  const getUserDetectionInfoList = async () => {
    const { responseCode, responseData } = await requestGetUserDetectionInfoList({})
    if (responseCode === HttpCodeEnum.SUCCESS) {
      data.value = responseData
      data.value.forEach((item: any) => {
        item.record = getStatusDetection(item.detectionType)[item.status as STATUS_DETECTION_ENUM] || {}
        item.detectionInfoId = item.id
      })
      console.log('data: ', data.value)
    }
  }

  const getStatusDetection = (type: SCAN_TYPE) => {
    return {
      [STATUS_DETECTION_ENUM.INSTRUCTION]: {
        title: '未绑定',
        content: '未绑定当前码',
        btn: '去绑定',
        handle: (resData: any) => {
          uni.navigateTo({
            url: `${scanResultLink[type][STATUS_DETECTION_ENUM.INSTRUCTION]}?codeValue=${resData.codeValue}`,
          })
        },
      },
      [STATUS_DETECTION_ENUM.QUESTIONNAIRE]: {
        title: '待填写问卷',
        content: '请按要求填写问卷',
        btn: '填写问卷',
        handle: (resData: any) => {
          if (!resData.publishId) {
            uni.showToast({ title: 'publishId为空', icon: 'none' })
            return
          }
          uni.navigateTo({
            url: `${scanResultLink[type][STATUS_DETECTION_ENUM.QUESTIONNAIRE]}?publishId=${resData.publishId}&detectionInfoId=${resData.detectionInfoId}`,
          })
        },
      },
      [STATUS_DETECTION_ENUM.POSITION]: {
        title: '位置待确认',
        content: '请按要求确认位置',
        btn: '位置确认',
        handle: (resData: any) => {
          if (!resData.detectionInfoId) {
            uni.showToast({ title: 'detectionInfoId为空', icon: 'none' })
            return
          }
          uni.navigateTo({
            url: `${scanResultLink[type][STATUS_DETECTION_ENUM.POSITION]}?detectionInfoId=${resData.detectionInfoId}`,
          })
        },
      },
      [STATUS_DETECTION_ENUM.COLLECT_SAMPLES]: scanTypeResult[type],
      [STATUS_DETECTION_ENUM.EXPRESS]: {
        title: '快递待取件',
        content: '请联系快递员上门取件',
        btn: '查看问卷',
        handle: (resData: any) => {
          if (!resData.detectionInfoId) {
            uni.showToast({ title: 'detectionInfoId为空', icon: 'none' })
            return
          }
          uni.navigateTo({
            url: `/pages/detection/express?detectionInfoId=${resData.detectionInfoId}`,
          })
        },
      },
      [STATUS_DETECTION_ENUM.TEST_REPORT]: {
        title: '等待检测报告',
        content: '样本已提交，等待检测报告',
        btn: '查看问卷',
        handle: (resData: any) => {
          // if (!resData.publishId || !resData.questionnaireRecordId) {
          //   uni.showToast({ title: `${resData.publishId ? 'questionnaireRecordId' : 'publishId'}为空`, icon: 'none' })
          //   return
          // }
          if (resData.scanFlag) {
            uni.showToast({ title: '样本已提交，等待检测报告', icon: 'none' })
            return
          }
          uni.navigateTo({
            url: `/pages/detection/preview?publishId=${resData.publishId}&recordID=${resData.questionnaireRecordId}`,
          })
        },
      },
    }
  }

  const scan = async (detectionType: SCAN_TYPE) => {
    if (!isLogin.value) {
      uni.navigateTo({ url: '/pages/sys/login/login' })
      return
    }
    wx.scanCode({
      success: async (res) => {
        console.log('scanCode: ', res)
        userInfoStore.detectionType = detectionType
        const { responseCode, responseData, responseMessage } = await requestScan({ codeValue: res.result, detectionType })
        console.log('codeValue:' + res.result + '-----detectionType' + 1)
        if (responseCode === HttpCodeEnum.SUCCESS) {
          let record = getStatusDetection(detectionType)[responseData.status as STATUS_DETECTION_ENUM] || {}
          responseData.codeValue = res.result
          responseData.scanFlag = true
          record.handle && record.handle(responseData)
        } else {
          uni.showToast({ title: responseMessage, icon: 'none' })
        }
      },
      fail(e) {
        // uni.showToast({ title: '扫码失败', icon: 'none' })
        console.log('扫码失败: ', console.log(e))
      },
    })
  }
  /** 产品溯源扫码 */
  const scanProduct = async () => {
    if (!isLogin.value) {
      uni.navigateTo({ url: '/pages/sys/login/login' })
      return
    }
    wx.scanCode({
      success: async (res) => {
        const { responseCode, responseData, responseMessage } = await requestProductScan({ codeValue: res.result, detectionType: SCAN_TYPE.SCAN_PRODUCT })
        if (responseCode === HttpCodeEnum.SUCCESS) {
          if (!responseData.extInfo) {
            uni.showModal({ title: '该码未上传报告', icon: 'none', confirmText: '确定', confirmColor: '#08979C', showCancel: false })
            return
          }
          if (isImage(responseData.extInfo)) {
            uni.navigateTo({ url: `/pages/sys/reportDetail?reportUrl=${responseData.extInfo}` })
          } else {
            openDocument(responseData.extInfo)
          }
        } else {
          uni.showToast({ title: responseMessage, icon: 'none' })
        }
      },
      fail(e) {
        // uni.showToast({ title: '扫码失败', icon: 'none' })
        console.log('扫码失败: ', console.log(e))
      },
    })
  }

  /**
   * 跳转视频号
   */
  //const goVideo = () => uni.navigateTo({ url: `/pages/common/video?src=${commonVideo.useHelp}` })
  const goVideo = () => {
    const { finderUserName, feedId } = env
    uni.openChannelsActivity({ finderUserName, feedId: feedId.gutAndHealth })
  }

  /** 页面分享 */
  onShareAppMessage(() => {
    return {
      title: SHARE_HOME_TITLE,
      imageUrl: SHARE_HOME_IMAGE,
      path: HOME_PAGE,
    }
  })
</script>

<template>
  <view>
    <image @click="goVideo" class="video" id="videoImg" mode="widthFix" :src="microbiotaPng.videoImg" />
    <!-- <image class="logo" mode="widthFix" :src="indexSortPng.indexLogo" /> -->
    <view class="scanning-area">
      <view class="left_con" :style="{ backgroundImage: `url(${indexSortPng.indexSort1})` }" @click="scan(SCAN_TYPE.SCAN_DETECTION)">
        <view class="title">菌群检测扫码</view>
        <text class="des"> 扫码开始</text>
      </view>
      <view class="right_con">
        <view class="left_con" :style="{ backgroundImage: `url(${indexSortPng.indexSort2})` }" @click="scan(SCAN_TYPE.SCAN_RECRUIT)">
          <view class="title line_center">供体招募</view>
        </view>
        <view class="left_con" :style="{ backgroundImage: `url(${indexSortPng.indexSort3})` }" @click="scanProduct">
          <view class="title line_center">产品溯源</view>
        </view>
        <!-- <view class="scan-btn" @click="scan">
          <image class="scancode-icon" :src="microbiotaPng.scanSode" />
          扫码绑定
        </view> -->
      </view>
    </view>
    <view class="content">
      <view class="task-item" v-if="!data.length">
        <view class="task-item-header">
          <view>
            <image class="task-item-icon" :src="microbiotaPng.taskIcon" />
            <text class="task-item-title">肠道菌群检测</text>
          </view>
          <view class="task-item-status">{{ isLogin ? '暂无任务' : '未登录' }}</view>
        </view>
        <view class="task-item-content no-task">
          <image class="no-task-img" :src="microbiotaPng.noTask" />
          <br />
          <text class="scanning-tips">点击扫一扫，扫码开始检测</text>
        </view>
      </view>
      <view v-else>
        <view class="task-item" v-for="item in data" :key="item.id">
          <view class="task-item-header">
            <view>
              <image class="task-item-icon" :src="microbiotaPng.taskIcon" />
              <text class="task-item-title">{{ scanTypeDesc[item.detectionType] }}</text>
            </view>
            <text class="task-item-status">{{ item.record.title }}</text>
          </view>
          <view class="task-item-content">
            <view class="content-title">{{ item.record.content }}</view>
            <view class="content-info">
              <text>扫码时间</text>
              <text>{{ item.createdTime }}</text>
            </view>
            <view class="action">
              <!-- <text class="action-btn grey">查看问卷</text> -->
              <text class="action-btn" @click="(userInfoStore.detectionType = item.detectionType), item.record.handle(item)">{{ item.record.btn }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- <button @click="toDetection">检测须知</button> -->
    </view>
  </view>
</template>

<style lang="less">
  .video {
    width: 100%;
  }

  .logo{
    position: absolute;
    top: 100rpx;
    left: 40rpx;
    width: 168rpx;
  }

  .file {
    width: 100%;
    margin-top: 32rpx;
  }

  .scanning-area {
    position: relative;
    display: flex;
    height: 338rpx;
    padding: 32rpx 16rpx;
    margin-top: -36rpx;
    text-align: center;
    background: linear-gradient(180deg, #e1fffb 0%, #f1f3f5 100%);
    border-radius: 32rpx;

    .left_con {
      flex: 1;
      text-align: left;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      border-bottom-right-radius: 30px;

      .title {
        padding: 17px 0 0 25px;
        font-size: 18px;
        color: #fff;
      }

      .des {
        padding: 17px 0 0 25px;
        font-size: 12px;
        color: rgb(255 255 255 / 65%);
      }

      .line_center {
        line-height: 50rpx;
      }
    }

    .right_con {
      display: flex;
      flex: 1;
      flex-direction: column;

      .scan-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        font-size: 36rpx;
        color: #014951;
        background: linear-gradient(to bottom, #87e8de, #13c2c2);
        border-radius: 84rpx;
        box-shadow:
          0 4px 8px 0 rgb(19 194 194 / 50%),
          inset 0 -1px 3px 0 rgb(255 255 255 / 50%);

        .scancode-icon {
          width: 40rpx;
          height: 40rpx;
          margin-right: 16rpx;
        }
      }
    }
  }

  .content {
    padding: 0 32rpx 16rpx;

    .task-item {
      margin-bottom: 32rpx;
      border: 1px solid #fff;
      border-radius: 32rpx;

      .task-item-header {
        display: flex;
        justify-content: space-between;
        height: 92rpx;
        padding: 28rpx 32rpx 0 16rpx;
        font-size: 28rpx;
        background: #e1fffb;
        border-top-left-radius: 32rpx;
        border-top-right-radius: 32rpx;

        .task-item-icon {
          position: relative;
          top: -12rpx;
          width: 64rpx;
          height: 64rpx;
        }

        .task-item-title {
          position: relative;
          top: -32rpx;
          color: #08979c;
        }

        .task-item-status {
          color: #002329;
        }
      }

      .task-item-content {
        position: relative;
        padding: 32rpx;
        background: #fff;
        border-radius: 32rpx;

        .content-title {
          font-size: 32rpx;
          color: #1d2129;
        }

        .content-info {
          margin: 16rpx 0 48rpx;
          font-size: 24rpx;

          & > text:nth-of-type(1) {
            margin-right: 32rpx;
            color: #86909c;
          }
        }

        .action {
          text-align: right;

          .action-btn {
            width: 166rpx;
            height: 64rpx;
            padding: 10rpx 32rpx;
            margin-left: 16rpx;
            font-size: 28rpx;
            color: #08979c;
            border: 1px solid #08979c;
            border-radius: 32rpx;

            &.grey {
              color: #4e5969;
              border-color: #e0e1e6;
            }
          }
        }

        &.no-task {
          text-align: center;

          .no-task-img {
            width: 240rpx;
            height: 160rpx;
          }

          .scanning-tips {
            color: #1d2129;
          }
        }

        &::before {
          position: absolute;
          top: 0;
          left: 0;
          z-index: -1;
          width: 100%;
          height: 40rpx;
          content: ' ';
          background: #e1fffb;
        }
      }
    }
  }
</style>
